{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "015d2026",
   "metadata": {},
   "outputs": [],
   "source": [
    "deployment = \"gpt4\"\n",
    "model = \"gpt-4\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "522d3690",
   "metadata": {},
   "source": [
    "# IaC：生成 Terraform 脚本"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "3a4fc103",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.chat_models import AzureChatOpenAI\n",
    "from langchain.memory import ConversationBufferWindowMemory\n",
    "from langchain.chains import ConversationChain\n",
    "\n",
    "llm = AzureChatOpenAI(deployment_name=deployment, temperature=0.3, max_tokens=1000,\n",
    "                     streaming=True)\n",
    "\n",
    "memory = ConversationBufferWindowMemory(k=10) \n",
    "\n",
    "\n",
    "def get_response(input):\n",
    "    conversation_with_memory = ConversationChain(\n",
    "        llm=llm, \n",
    "        memory=memory,\n",
    "        verbose=False\n",
    "    )\n",
    "    return conversation_with_memory.predict(input=input)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "6ee1e549",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "很抱歉，由于我是一个文本生成的AI，我无法直接提供代码或脚本。但是我可以告诉你大概的步骤和你可能需要的资源。\n",
      "\n",
      "首先，你需要一个Terraform的配置文件。这个文件会定义你要创建的资源，比如EKS集群，以及这些资源的配置。\n",
      "\n",
      "你可以参考以下的基本结构来创建你的Terraform脚本：\n",
      "\n",
      "```hcl\n",
      "provider \"aws\" {\n",
      "  region = \"us-west-2\"\n",
      "}\n",
      "\n",
      "module \"eks\" {\n",
      "  source          = \"terraform-aws-modules/eks/aws\"\n",
      "  cluster_name    = \"my-eks-cluster\"\n",
      "  cluster_version = \"1.17\"\n",
      "  subnets         = [\"subnet-abcde012\", \"subnet-bcde012a\", \"subnet-fghi345a\"]\n",
      "  vpc_id          = \"vpc-abcde012\"\n",
      "\n",
      "  node_groups = {\n",
      "    eks_nodes = {\n",
      "      desired_capacity = 2\n",
      "      max_capacity     = 10\n",
      "      min_capacity     = 1\n",
      "\n",
      "      instance_type = \"m4.large\"\n",
      "      key_name      = \"my-key-name\"\n",
      "    }\n",
      "  }\n",
      "}\n",
      "```\n",
      "\n",
      "这个脚本会创建一个名为\"my-eks-cluster\"的EKS集群，版本为1.17。集群会在指定的VPC和子网中创建，并且会创建一个名为\"eks_nodes\"的节点组，这个节点组的实例类型为\"m4.large\"，并且会使用名为\"my-key-name\"的密钥对。\n",
      "\n",
      "请注意，这只是一个基本的示例，你可能需要根据你的实际需求来修改这个脚本。例如，你可能需要添加更多的配置选项，或者创建更多的资源。\n",
      "\n",
      "在你运行这个脚本之前，你需要确保你已经安装了Terraform，并且你的AWS账户已经有了足够的权限来创建这些资源。你也需要确保你已经设置了正确的AWS凭证，Terraform可以使用这些凭证来访问你的AWS账户。\n",
      "\n",
      "你可以在Terraform的官方文档中找到更多关于如何使用Terraform来创建AWS资源的信息。\n"
     ]
    }
   ],
   "source": [
    "print(get_response(\"\"\"\n",
    "给我一个terraform脚本示例，用来创建一个AWS EKS集群\n",
    "\"\"\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "926b5f95",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "在阿里云上创建Kubernetes集群，你需要使用阿里云的Terraform提供者。以下是一个基本的Terraform脚本示例，用于在阿里云上创建一个Kubernetes集群：\n",
      "\n",
      "```hcl\n",
      "provider \"alicloud\" {\n",
      "  access_key = \"<your-access-key>\"\n",
      "  secret_key = \"<your-secret-key>\"\n",
      "  region     = \"cn-hangzhou\"\n",
      "}\n",
      "\n",
      "resource \"alicloud_cs_managed_kubernetes\" \"k8s\" {\n",
      "  name_prefix           = \"my-k8s-cluster\"\n",
      "  worker_instance_types = [\"ecs.g5.large\"]\n",
      "  worker_number         = 2\n",
      "  password              = \"<your-password>\"\n",
      "  pod_cidr              = \"172.20.0.0/16\"\n",
      "  service_cidr          = \"172.21.0.0/20\"\n",
      "  install_cloud_monitor = true\n",
      "}\n",
      "```\n",
      "\n",
      "这个脚本会创建一个名为\"my-k8s-cluster\"的Kubernetes集群，工作节点的实例类型为\"ecs.g5.large\"，工作节点的数量为2。集群的Pod CIDR为\"172.20.0.0/16\"，Service CIDR为\"172.21.0.0/20\"，并且会安装云监控服务。\n",
      "\n",
      "请注意，你需要替换`<your-access-key>`、`<your-secret-key>`和`<your-password>`为你自己的阿里云Access Key、Secret Key和密码。\n",
      "\n",
      "同样，这只是一个基本的示例，你可能需要根据你的实际需求来修改这个脚本。例如，你可能需要添加更多的配置选项，或者创建更多的资源。\n",
      "\n",
      "在你运行这个脚本之前，你需要确保你已经安装了Terraform，并且你的阿里云账户已经有了足够的权限来创建这些资源。你也需要确保你已经设置了正确的阿里云凭证，Terraform可以使用这些凭证来访问你的阿里云账户。\n",
      "\n",
      "你可以在Terraform的官方文档中找到更多关于如何使用Terraform来创建阿里云资源的信息。\n"
     ]
    }
   ],
   "source": [
    "print(get_response(\"\"\"\n",
    "将上面的script改写为适合阿里云的\n",
    "\"\"\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fd554a33",
   "metadata": {},
   "source": [
    "# 生成应用部署文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "1099baf9",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "def work_on(input):\n",
    "    response = openai.ChatCompletion.create(\n",
    "        engine=deployment, # engine = \"deployment_name\".\n",
    "        messages=[\n",
    "            {\"role\": \"system\", \"content\": \"You are a senior software engineer.\"},   \n",
    "            {\"role\": \"user\", \"content\": input}\n",
    "        ],\n",
    "        temperature = 0.9, \n",
    "        max_tokens = 1000,\n",
    "      )\n",
    "    return response.choices[0].message.content"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "277518ff",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "以下是一个满足您需求的 Kubernetes 服务部署 yaml 文件的示例:\n",
      "\n",
      "```yaml\n",
      "apiVersion: v1\n",
      "kind: Namespace\n",
      "metadata:\n",
      "  name: service\n",
      "\n",
      "---\n",
      "apiVersion: v1\n",
      "kind: ServiceAccount\n",
      "metadata:\n",
      "  name: nginx-service-account\n",
      "  namespace: service\n",
      "\n",
      "---\n",
      "apiVersion: apps/v1\n",
      "kind: Deployment\n",
      "metadata:\n",
      "  name: nginx-deployment\n",
      "  namespace: service\n",
      "spec:\n",
      "  replicas: 1\n",
      "  selector:\n",
      "    matchLabels:\n",
      "      app: nginx\n",
      "  template:\n",
      "    metadata:\n",
      "      labels:\n",
      "        app: nginx\n",
      "    spec:\n",
      "      serviceAccountName: nginx-service-account\n",
      "      containers:\n",
      "      - name: nginx\n",
      "        image: nginx:1.14.2\n",
      "        ports:\n",
      "        - containerPort: 80\n",
      "        readinessProbe:\n",
      "          httpGet:\n",
      "            path: /\n",
      "            port: 80\n",
      "          initialDelaySeconds: 5\n",
      "          periodSeconds: 5\n",
      "        livenessProbe:\n",
      "          httpGet:\n",
      "            path: /\n",
      "            port: 80\n",
      "          initialDelaySeconds: 15\n",
      "          periodSeconds: 20\n",
      "        lifecycle:\n",
      "          preStop:\n",
      "            exec:\n",
      "              command: [\"/bin/sh\",\"-c\",\"nginx -s quit; while killall -0 nginx; do sleep 1; done\"]\n",
      "---\n",
      "\n",
      "apiVersion: v1\n",
      "kind: Service\n",
      "metadata:\n",
      "  name: nginx-service\n",
      "  namespace: service\n",
      "spec:\n",
      "  selector:\n",
      "    app: nginx\n",
      "  ports:\n",
      "  - protocol: TCP\n",
      "    port: 8080\n",
      "    targetPort: 80\n",
      "```\n",
      "这个yaml文件的关键部分包括：\n",
      "\n",
      "- 命名空间（namespace）的定义\n",
      "- 服务帐户（Service Account）的定义\n",
      "- 容器部署（deployment）的定义，包含 readiness 和 liveness probes\n",
      "- 服务（Service）的定义，用于映射容器的端口到外部端口 8080。\n",
      "- 在容器生命周期的 preStop 配置中，我们添加了一个命令以优雅地关闭Nginx。\n",
      "\n",
      "请确保对应的Nginx镜像在部署的Kubernetes要访问的镜像仓库中。我这里使用的是公开的Nginx镜像，版本为1.14.2。\n"
     ]
    }
   ],
   "source": [
    "print(work_on(\"\"\"\n",
    "编写kubernetes部署文件（yaml）用于部署Nginx服务，服务端口8080\n",
    "满足以下的要求\n",
    "1. 部署的namespace为”service“\n",
    "2. 包含readiness及liveness probe\n",
    "3. 采用一个独立的service account运行\n",
    "4. 包含完美终止（graceful termination）配置\n",
    "\"\"\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "29aac7a5",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain import PromptTemplate, OpenAI, LLMChain\n",
    "\n",
    "from langchain.chat_models import AzureChatOpenAI\n",
    "# from langchain.chat_models import ChatOpenAI #直接访问OpenAI的GPT服务\n",
    "\n",
    "def create_k8s_config(requirements):\n",
    "    prompt_template = \"\"\"\n",
    "    根据以下用户需求：\n",
    "    \"{requirements}\"\n",
    "    编写kubernetes部署文件（yaml), \n",
    "    满足以下的要求\n",
    "    1. 部署的namespace为”service“\n",
    "    2. 包含readiness及liveness probe\n",
    "    3. 采用一个独立的service account运行\n",
    "    4. 包含完美终止（graceful termination）配置\n",
    "    \"\"\"\n",
    "\n",
    "    #llm = ChatOpenAI(model_name=\"gpt-4\", temperature=0) #直接访问OpenAI的GPT服务\n",
    "    llm = AzureChatOpenAI(deployment_name = deployment, model_name=model, temperature=0, max_tokens=200) # 通过Azure的OpenAI服务\n",
    "    llm_chain = LLMChain(\n",
    "        llm=llm,\n",
    "        prompt=PromptTemplate.from_template(prompt_template)\n",
    "    )\n",
    "    return llm_chain.run(requirements)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "3980537d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "以下是一个满足上述要求的Kubernetes部署文件示例：\n",
      "\n",
      "```yaml\n",
      "apiVersion: v1\n",
      "kind: Namespace\n",
      "metadata:\n",
      "  name: service\n",
      "---\n",
      "apiVersion: v1\n",
      "kind: ServiceAccount\n",
      "metadata:\n",
      "  name: nginx-service-account\n",
      "  namespace: service\n",
      "---\n",
      "apiVersion: apps/v1\n",
      "kind: Deployment\n",
      "metadata:\n",
      "  name: nginx-deployment\n",
      "  namespace: service\n",
      "spec:\n",
      "  replicas: 1\n",
      "  selector:\n",
      "    matchLabels:\n",
      "      app: nginx\n",
      "  template:\n",
      "    metadata:\n",
      "      labels:\n",
      "        app: nginx\n",
      "    spec:\n",
      "      serviceAccountName: nginx-service-account\n",
      "      containers:\n",
      "      - name: nginx\n",
      "        image: nginx:1.14.2\n",
      "        ports:\n",
      "        - containerPort: 8080\n",
      "        readinessProbe:\n",
      "          httpGet:\n",
      "            path: /\n",
      "            port: 8080\n",
      "          initialDelaySeconds: 5\n",
      "          period\n"
     ]
    }
   ],
   "source": [
    "print(create_k8s_config(\"部署Nginx服务，服务端口8080\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bdf10a6a",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
